﻿/**
* File: XmglxmxxlcService.cs
* Author: 汪杰
* Create Time:2025/2/24 15:30:47
* Email:15200358008@139.com
* 代码由TMCodeGenerator自动生成
**/
using AutoMapper;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using JSLCloud.Attributes;
using JSLCloud.App.Models.Xmglxmxxlc;
using JSLCloud.DBModel;
using JSLCloud.Framework;
using JSLCloud.Models;
using JSLCloud.Utilities.SqlSugar;
using JSLCloud.Utilities.WebApi;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using JSLCloud.App.Models.Xmglxmxxpc;


namespace JSLCloud.App.Mes.Service
{
    /// <summary>
    /// IXmglxmxxlcService 实现类
    /// </summary>
    [UseDI(ServiceLifetime.Scoped,typeof(IXmglxmxxlcService))]
    public class XmglxmxxlcService : IXmglxmxxlcService
    {
        private readonly IDbContext _db;//数据库操作实例对象
        private readonly ILogger<XmglxmxxlcService> _log;//日志操作实例对象
        private readonly IMapper _mapper;//AutoMapper实例
        
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dbContext"></param>
        /// <param name="logger"></param>
        /// <param name="mapper"></param>
        public XmglxmxxlcService(IDbContext dbContext, ILogger<XmglxmxxlcService> logger,IMapper mapper)
        {
            _db = dbContext;
            _log = logger;
            _mapper = mapper;
        }
        
        /// <summary>
        /// 获取xm_gl_xmxxlc数据
        /// </summary>
        /// <param name="requestObject">返回响应结果对象，包括响应代码，查询操作结果</param>
        /// <returns></returns>
        public async Task<ResponseObject<List<XmglxmxxlcQueryModel>>> GetAsync(RequestGet requestObject)
        {
            try
            {
                List<XmglxmxxlcQueryModel> queryData = null;//查询结果集对象
                RefAsync<int> totalNumber = -1;//总记录数
                var query = _db.Instance.Queryable<XmglxmxxlcDbModel>();
                //查询条件
                if (requestObject.QueryConditions != null && requestObject.QueryConditions.Count > 0)
                {
                    var conditionals = SqlSugarUtil.GetConditionalModels(requestObject.QueryConditions);
                    query.Where(conditionals);
                }
                
                //查询未删除数据
                query.Where("DELETEFLAG = 0");
                
                //排序条件
                if(requestObject.OrderByConditions != null && requestObject.OrderByConditions.Count > 0)
                {
                    foreach (var item in requestObject.OrderByConditions)
                    {
                        if (item.Condition.ToLower() != "asc" 
                            && item.Condition.ToLower() != "desc") continue;
                        query.OrderBy($"{item.Column} {item.Condition}");
                    }
                }
                
                //执行查询
                if (requestObject.IsPaging)
                {
                    queryData = await query.Select(
						(t) => new XmglxmxxlcQueryModel 
						{
							ID = t.ID,
							Createid = t.Createid,
							Createname = t.Createname,
							Createtime = t.Createtime,
							Updateid = t.Updateid,
							Updatename = t.Updatename,
							Updatetime = t.Updatetime,
							Deleteflag = t.Deleteflag,
							Xmid = t.Xmid,
							Lcmc = t.Lcmc,
							Lcxh = t.Lcxh,
							Ksrq = t.Ksrq,
							Jsrq = t.Jsrq,
							Shts = t.Shts,
							Sfxcsh = t.Sfxcsh,
							Khyq = t.Khyq,
							Bz = t.Bz,
							Lczt = t.Lczt,
							Lcqrr = t.Lcqrr,
							Lcqrsj = t.Lcqrsj,
							Shy = t.Shy,
							Shyid = t.Shyid,
							Pcr = t.Pcr,
							Pcsj = t.Pcsj,
						})
                        .ToPageListAsync(requestObject.PageIndex, requestObject.PageSize, totalNumber);
                }
                else
                {
                    queryData = await query.Select(
						(t) => new XmglxmxxlcQueryModel 
						{
							ID = t.ID,
							Createid = t.Createid,
							Createname = t.Createname,
							Createtime = t.Createtime,
							Updateid = t.Updateid,
							Updatename = t.Updatename,
							Updatetime = t.Updatetime,
							Deleteflag = t.Deleteflag,
							Xmid = t.Xmid,
							Lcmc = t.Lcmc,
							Lcxh = t.Lcxh,
							Ksrq = t.Ksrq,
							Jsrq = t.Jsrq,
							Shts = t.Shts,
							Sfxcsh = t.Sfxcsh,
							Khyq = t.Khyq,
							Bz = t.Bz,
							Lczt = t.Lczt,
							Lcqrr = t.Lcqrr,
							Lcqrsj = t.Lcqrsj,
							Shy = t.Shy,
							Shyid = t.Shyid,
							Pcr = t.Pcr,
							Pcsj = t.Pcsj,
						})
                        .ToListAsync();
                }
                    
                //返回执行结果
                return ResponseUtil<List<XmglxmxxlcQueryModel>>.SuccessResult(queryData, totalNumber);
            }
            catch (Exception ex)
            {
                //返回查询异常结果
                return ResponseUtil<List<XmglxmxxlcQueryModel>>.FailResult(null, ex.Message);
            }
        }

        /// <summary>
        /// 获取xm_gl_xmxxlc数据
        /// </summary>
        /// <param name="requestObject">返回响应结果对象，包括响应代码，查询操作结果</param>
        /// <returns></returns>
        public async Task<ResponseObject<List<XmglxmxxlcQuery2Model>>> GetProcessAsync(RequestGet requestObject)
        {
            try
            {
                List<XmglxmxxlcQuery2Model> queryData = null;//查询结果集对象
                RefAsync<int> totalNumber = -1;//总记录数
                var query = _db.Instance.Queryable<XmglxmxxlcDbModel>();
                //查询条件
                if (requestObject.QueryConditions != null && requestObject.QueryConditions.Count > 0)
                {
                    var conditionals = SqlSugarUtil.GetConditionalModels(requestObject.QueryConditions);
                    query.Where(conditionals);
                }

                //查询未删除数据
                query.Where("DELETEFLAG = 0");

                //排序条件
                if (requestObject.OrderByConditions != null && requestObject.OrderByConditions.Count > 0)
                {
                    foreach (var item in requestObject.OrderByConditions)
                    {
                        if (item.Condition.ToLower() != "asc"
                            && item.Condition.ToLower() != "desc") continue;
                        query.OrderBy($"{item.Column} {item.Condition}");
                    }
                }

                //执行查询
                queryData = await query.Select((t) => 
                    new XmglxmxxlcQuery2Model{
                        ID = t.ID,
                        Xmid = t.Xmid,
                        Lcmc = t.Lcmc,
                        Lcxh = t.Lcxh,                            
                    })
                    .ToListAsync();

                queryData.ForEach(p =>
                {
                    p.Data = _db.Instance.Queryable<XmglxmxxpcDbModel>()
                        .Select(p1 => new XmglxmxxpcQueryModel
                        {
                            ID = p1.ID,
                            Xmid = p1.Xmid,
                            Xmlcid = p1.Xmlcid,
                            Shy = p1.Shy,
                            Shyid = p1.Shyid,
                            Kssj = p1.Kssj,
                            Jssj = p1.Jssj,
                            Rt = p1.Rt
                        })
                        .Where(p1 => p1.Xmid == p.Xmid && p1.Xmlcid == p.ID)
                        .ToList();

                    if(p.Data == null  || p.Data.Count < 1)
                    {
                        p.Data.Add(new XmglxmxxpcQueryModel
                        {
                            ID = 0,
                            Xmid = p.Xmid,
                            Xmlcid = p.ID,
                            Kssj = DateTime.Now,
                            Jssj = DateTime.Now
                        });
                    }
                });

                //返回执行结果
                return ResponseUtil<List<XmglxmxxlcQuery2Model>>.SuccessResult(queryData, totalNumber);
            }
            catch (Exception ex)
            {
                //返回查询异常结果
                return ResponseUtil<List<XmglxmxxlcQuery2Model>>.FailResult(null, ex.Message);
            }
        }

        /// <summary>
        /// 新增xm_gl_xmxxlc数据
        /// </summary>
        /// <param name="requestObject">返回响应结果对象，包括响应代码，新增操作结果</param>
        /// <returns></returns>
        public async Task<ResponseObject<bool>> PostAsync(RequestPost<XmglxmxxlcAddModel> requestObject)
        {
            try
            {
                //如果没有新增数据，返回错误信息
                if (requestObject.PostData == null && requestObject.PostDataList == null)
                    return ResponseUtil<bool>.FailResult(false, "PostData,PostDataList不能都为null");
                var result = false;
                //批量新增的优先级高于单条数据新增，且只会执行一个新增操作
                if(requestObject.PostDataList != null && requestObject.PostDataList.Count > 0)
                {
                    var addList = _mapper.Map<List<XmglxmxxlcDbModel>>(requestObject.PostDataList);
                    result = await _db.Instance.Insertable(addList).ExecuteCommandAsync() > 0;
                }
                else
                {
                    var addModel = _mapper.Map<XmglxmxxlcDbModel>(requestObject.PostData);
                    result = await _db.Instance.Insertable(addModel).ExecuteCommandAsync() > 0;
                }
                //返回执行结果
                return result ? ResponseUtil<bool>.SuccessResult(true) : ResponseUtil<bool>.FailResult(false, "新增数据失败!");
            }
            catch(Exception ex)
            {
                //返回异常结果
                return ResponseUtil<bool>.FailResult(false, ex.Message);
            }
        }
        
        /// <summary>
        /// 修改xm_gl_xmxxlc数据
        /// </summary>
        /// <param name="requestObject">返回响应结果对象，包括响应代码，修改操作结果</param>
        /// <returns></returns>
        public async Task<ResponseObject<bool>> PutAsync(RequestPut<XmglxmxxlcEditModel> requestObject)
        {
            try
            {
                //执行结果
                var result = false;
                //没有修改信息，返回错误信息
                if (requestObject.PostDataList == null && requestObject.PostData == null)
                    return ResponseUtil<bool>.FailResult(false, "PostData,PostDataList不能都为null");
                //批量更新优先级高于单记录更新
                if (requestObject.PostDataList != null && requestObject.PostDataList.Count > 0)
                {
                    //批量更新
                    var editList = _mapper.Map<List<XmglxmxxlcDbModel>>(requestObject.PostDataList);
                    result = await _db.Instance.Updateable(editList)
                        .IgnoreColumns(p => new { p.Createid, p.Createtime,p.Createname })
                        .ExecuteCommandAsync() > 0;
                }
                else
                {
                    //单记录更新
                    var editModel = _mapper.Map<XmglxmxxlcDbModel>(requestObject.PostData);
                    result = await _db.Instance.Updateable(editModel)
                        .IgnoreColumns(p => new { p.Createid, p.Createtime,p.Createname })
                        .ExecuteCommandAsync() > 0;
                }
                
                //返回执行结果
                return result ? ResponseUtil<bool>.SuccessResult(true) : ResponseUtil<bool>.FailResult(false, "修改数据失败!");
            }
            catch (Exception ex)
            {
                //返回异常结果
                return ResponseUtil<bool>.FailResult(false, ex.Message);
            }
        }

        /// <summary>
        /// 修改xm_gl_xmxxlc数据
        /// </summary>
        /// <param name="requestObject">返回响应结果对象，包括响应代码，修改操作结果</param>
        /// <returns></returns>
        public async Task<ResponseObject<bool>> ExecAsync(RequestPut<XmglxmxxlcExecModel> requestObject)
        {
            try
            {
                //执行结果
                var result = false;
                //没有修改信息，返回错误信息
                if (requestObject.PostDataList == null && requestObject.PostData == null)
                    return ResponseUtil<bool>.FailResult(false, "PostData,PostDataList不能都为null");
                //批量更新优先级高于单记录更新
                if (requestObject.PostDataList != null && requestObject.PostDataList.Count > 0)
                {
                    //批量更新
                    var editList = _mapper.Map<List<XmglxmxxlcDbModel>>(requestObject.PostDataList);
                    result = await _db.Instance.Updateable(editList)
                        .UpdateColumns(p => new { p.Updateid, p.Updatetime, p.Updatename, p.Khyq, p.Bz})
                        .ExecuteCommandAsync() > 0;
                }
                else
                {
                    //单记录更新
                    var editModel = _mapper.Map<XmglxmxxlcDbModel>(requestObject.PostData);
                    result = await _db.Instance.Updateable(editModel)
                        .UpdateColumns(p => new { p.Updateid, p.Updatetime, p.Updatename, p.Khyq, p.Bz })
                        .ExecuteCommandAsync() > 0;
                }

                //返回执行结果
                return result ? ResponseUtil<bool>.SuccessResult(true) : ResponseUtil<bool>.FailResult(false, "修改数据失败!");
            }
            catch (Exception ex)
            {
                //返回异常结果
                return ResponseUtil<bool>.FailResult(false, ex.Message);
            }
        }

        /// <summary>
        /// 修改xm_gl_xmxxlc数据
        /// </summary>
        /// <param name="requestObject">返回响应结果对象，包括响应代码，修改操作结果</param>
        /// <returns></returns>
        public async Task<ResponseObject<bool>> EndProcessAsync(RequestPut<XmglxmxxlcExecModel> requestObject)
        {
            try
            {
                //执行结果
                var result = false;
                //没有修改信息，返回错误信息
                if (requestObject.PostDataList == null && requestObject.PostData == null)
                    return ResponseUtil<bool>.FailResult(false, "PostData,PostDataList不能都为null");

                //单记录更新
                var editModel = _mapper.Map<XmglxmxxlcDbModel>(requestObject.PostData);
                
                result = await _db.Instance.Updateable(editModel)
                    .UpdateColumns(p => new { p.Lczt, p.Lcqrr, p.Lcqrsj })
                    .ExecuteCommandAsync() > 0;
                var xmid = await _db.Instance.Queryable<XmglxmxxlcDbModel>().Where(p1 => p1.ID == editModel.ID).Select(p1 => p1.Xmid).FirstAsync();
                var notdone = await _db.Instance.Queryable<XmglxmxxlcDbModel>()
                    .Where(p => p.Xmid == xmid && p.Lczt == "N")
                    .ToListAsync();

                //流程都完成时，更新项目状态为已完成
                if(notdone == null && notdone.Count < 1)
                {
                    await _db.Instance.Updateable<XmglxmxxDbModel>()
                        .SetColumns(p => p.Xmzt == "Y")
                        .Where(p => p.ID == xmid)
                        .ExecuteCommandAsync();
                }
                    

                //返回执行结果
                return result ? ResponseUtil<bool>.SuccessResult(true) : ResponseUtil<bool>.FailResult(false, "修改数据失败!");
            }
            catch (Exception ex)
            {
                //返回异常结果
                return ResponseUtil<bool>.FailResult(false, ex.Message);
            }
        }

        /// <summary>
        /// 修改xm_gl_xmxxlc数据
        /// </summary>
        /// <param name="requestObject">返回响应结果对象，包括响应代码，修改操作结果</param>
        /// <returns></returns>
        public async Task<ResponseObject<bool>> SchedulingAsync(RequestPut<XmglxmxxlcSchedulingModel> requestObject)
        {
            try
            {
                //执行结果
                var result = false;
                //没有修改信息，返回错误信息
                if (requestObject.PostDataList == null && requestObject.PostData == null)
                    return ResponseUtil<bool>.FailResult(false, "PostData,PostDataList不能都为null");
                //批量更新优先级高于单记录更新
                if (requestObject.PostDataList != null && requestObject.PostDataList.Count > 0)
                {
                    //批量更新
                    var editList = _mapper.Map<List<XmglxmxxlcDbModel>>(requestObject.PostDataList);
                    result = await _db.Instance.Updateable(editList)
                        .UpdateColumns(p => new { p.Ksrq, p.Jsrq, p.Shy, p.Shyid, p.Pcr, p.Pcsj, p.Shts })
                        .ExecuteCommandAsync() > 0;
                }
                else
                {
                    //单记录更新
                    var editModel = _mapper.Map<XmglxmxxlcDbModel>(requestObject.PostData);
                    result = await _db.Instance.Updateable(editModel)
                        .UpdateColumns(p => new { p.Ksrq,p.Jsrq,p.Shy,p.Shyid,p.Pcr,p.Pcsj,p.Shts })
                        .ExecuteCommandAsync() > 0;
                }

                //返回执行结果
                return result ? ResponseUtil<bool>.SuccessResult(true) : ResponseUtil<bool>.FailResult(false, "修改数据失败!");
            }
            catch (Exception ex)
            {
                //返回异常结果
                return ResponseUtil<bool>.FailResult(false, ex.Message);
            }
        }

        /// <summary>
        /// 删除xm_gl_xmxxlc数据
        /// </summary>
        /// <param name="requestObject"></param>
        /// <returns></returns>
        public async Task<ResponseObject<bool>> DeleteAsync(RequestDelete<DeleteModel> requestObject)
        {
            try
            {
                //执行结果
                var result = false;
                //没有删除数据，返回错误信息
                if (requestObject.PostData == null && requestObject.PostDataList == null)
                    return ResponseUtil<bool>.FailResult(false, "PostData、PostDataList不能都为null");
                //批量删除的优先级高于单记录删除
                if (requestObject.PostDataList != null && requestObject.PostDataList.Count > 0)
                {
                    //批量删除
                    var ids = requestObject.PostDataList.Select(p => p.ID);
                    result = await _db.Instance.Updateable<XmglxmxxlcDbModel>()
                            .SetColumns(p => p.Deleteflag == 1)
                            .Where(p => ids.Contains(p.ID))
                            .ExecuteCommandAsync() > 0;
                }
                else
                {
                    //单记录删除
                    result = await _db.Instance.Updateable<XmglxmxxlcDbModel>()
                        .SetColumns(p => p.Deleteflag == 1)
                        .Where(p => p.ID == requestObject.PostData.ID)
                        .ExecuteCommandAsync() > 0;
                }
                //返回执行结果
                return result ? ResponseUtil<bool>.SuccessResult(true) : ResponseUtil<bool>.FailResult(false, "删除数据失败!");
            }
            catch (Exception ex)
            {
                //返回异常结果
                return ResponseUtil<bool>.FailResult(false, ex.Message);
            }
        }
        
    }
}
